%% Created Time:  Sun Apr 22 10:06:00 2012

-module(gain).
-export([get_url_s/3, 
		get_url_s/4, 
		headerCombine/1,
		retCombine/1,
		start/0, 
		stop/0, 
		a_receive/1, 
		get_url_a/1, 
		get_url_s/2,
	   	headerParse/2, 
		delete_space/2]).
-author("Charon <kevinlpcd@gmail.com>").
-vsn("gain 0.1").
-define(TRACE(X), io:format("TRACE ~p:~p ~p. [@~p]~n", [?MODULE, ?LINE, X, ?FILE])).

start() ->
	Stats = inets:start(),
	case Stats of 
			ok ->
				{ok,gain};
			_ ->
				{error, Stats}
	end.

get_url_s(URL,Option) ->
	get_url_s(URL, get, [], Option).

get_url_s(URL, Header, Option) ->
	get_url_s(URL, get, Header, Option).

get_url_s(URL, Method, Header, Option) ->
	case Method of
		get ->
			{ok, All} = httpc:request(Method, {URL, Header}, [], []);
		post ->
			{H, PostData} = Header,
			?TRACE(Header),
			{ok, All} = httpc:request(Method, {URL, H, "application/x-www-form-urlencoded", PostData}, [], [])
	end,
	{{Version, Code, Reason}, Headers, Body} = All,
	case Option of
		version ->
			Version;
		all ->
			All;
		code ->
			Code;
		reason ->
			Reason;
		headers ->
			Headers;
		body ->
			Body
	end.

get_url_a(URL) ->
	{ok, RequestID} = httpc:request(get, {URL, []}, [], [{sync, false}]),
	RequestID.

a_receive(RequestID) ->
	receive	
		{http, {RequestID, Result}} ->
			{ok,Result}
	after 
		500 ->
				error
 	end.

retCombine(All) ->
	{{Ver, Code, Reason}, Headers, Body} = All,
	H1 = string:join([Ver, integer_to_list(Code), Reason], " "),
	H2_P = headerCombine(Headers),
	H2 = string:join([H2_P], "\r\n"),
	Ret = string:join([tuple_to_list({H1}), H2, Body], "\r\n"),
%%	Ret = string:join([[H1 + "\r\n" |H2], Body], "\r\n"),
	Ret.

headerCombine([H | Header]) ->
	{Field, Value} = H,
	Fin1 = string:join([Field, Value], ": "),
	Fin = string:join([Fin1, "\r\n"], ""),
	[Fin |headerCombine(Header)];
	
headerCombine([]) ->
	[].
	
headerParse(Header, Method) ->
	[_|[_|H]] = re:split(Header, "[\r\n]", [{return, list}]),
	Pre_H = delete_space([], H),
	case Method of
		get ->
			Fin = formatHeader(Pre_H),
			Fin;
		post ->
			[Post | Pre_H1] = lists:reverse(Pre_H),
			Fin = formatHeader(lists:reverse(Pre_H1)),
			{Fin, Post}
	end.

delete_space(X, [X | T]) ->
	delete_space(X, T);
delete_space(X, [Y | T]) ->
	[Y | delete_space(X, T)];
delete_space(_,[]) ->
	[].

formatHeader([H | Pre_H]) ->
	[Field, Value]= re:split(H, ": ", [{return, list}]),
	[{Field, Value}|formatHeader(Pre_H)];
formatHeader([]) ->
	[].

stop() ->
	inets:stop().

